package breeze.pixel.weather.apps_util.views.mtextview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.annotation.Nullable;

import breeze.pixel.weather.R;
import breeze.pixel.weather.apps_util.utils.AppToolUtil;
import breeze.pixel.weather.apps_util.utils.appsettings.AppSettings;

@SuppressLint("AppCompatCustomView")
public class  MTextView extends TextView {
    private AppSettings sets;

    public MTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initByAttr(attrs);
    }
    public MTextView(Context context){
        super(context);
        init();
    }
    public MTextView(Context context,AttributeSet attributeSet){
        super(context,attributeSet);
        initByAttr(attributeSet);
    }

    private void init(){
        sets = AppSettings.getInstance(getContext());
        setTextSize(sets.getTextSize());
        setTextFont(sets.getTextFont());
    }

    private void initByAttr(AttributeSet attributeSet){
        sets = AppSettings.getInstance(getContext());
        @SuppressLint("Recycle")
        TypedArray typedArray = getContext().obtainStyledAttributes(attributeSet, R.styleable.MTextView);
        //int textSize = typedArray.getDimensionPixelSize(R.styleable.MTextView_textSize, sets.getTextFont());
        boolean notChangeSize = typedArray.getBoolean(R.styleable.MTextView_notChangeSize, false);
        int textStyle = typedArray.getInt(R.styleable.MTextView_textFont, sets.getTextFont());
        if(!notChangeSize){
            setTextSize(sets.getTextSize());
        }
        setTextFont(textStyle);
    }
    private void setTextFont(int font){
        /*
        * 0：无字体
        * 1：原本字体
        * 2：粗大字体
        * 3：自定义字体
         */
        if(font==-1){
            font = sets.getTextFont();
        }
        switch (font){
            case 0:
                setTypeface(null);
                break;
            case 1:
            default:
                setTypeface(createTypeFace("fonts/Pixel.ttf"));
                break;
            case 2:
                setTypeface(createTypeFace("fonts/Pixel2.ttf"));
                break;
            case 3:
                setTypeface(createTypeFaceByFile(AppToolUtil.getDiyFontPath(getContext())));
                break;
        }
    }
    private Typeface createTypeFace(String path){
        return Typeface.createFromAsset(getContext().getAssets(), path);
    }

    private Typeface createTypeFaceByFile(String path){
        return Typeface.createFromFile(path);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    public void setTextSize(float size) {
        super.setTextSize(size);
    }
}
